package com.pethub.dao.daoimpl;

import com.pethub.dao.PetDao;
import com.pethub.entity.Pet;
import com.pethub.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author harden
 * @version 1.0
 * @// TODO: 2017/12/4 0004
 */
@Repository("petDao")
public class PetDaoImpl implements PetDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    public Pet load(Integer id) throws Exception {
        return (Pet) getCurrentSession().load(Pet.class,id);
    }

    public Pet get(Integer id) throws Exception {
        return (Pet) getCurrentSession().get(Pet.class,id);
    }

    public List<Pet> findAll(String hql) throws Exception {
        return getCurrentSession().createQuery(hql).list();
    }

    public Pet save(Pet entity) throws Exception {
        Integer id= (Integer) getCurrentSession().save(entity);
        this.flush();
        return this.get(id);
    }

    public void saveOrUpdate(Pet entity) throws Exception {
        this.getCurrentSession().saveOrUpdate(entity);
    }

    public void delete(Integer id) throws Exception {
        this.getCurrentSession().delete(this.load(id));
    }

    public void flush() throws Exception {
        this.getCurrentSession().flush();
    }
    @SuppressWarnings("warnings")
    public List<Pet> findByUser(User user) throws Exception{
        return this.getCurrentSession().createQuery("from Pet p where p.user.id =?").setParameter(0,user.getId()).list();
    }
}
